package cn.mily.user.service.impl;

import cn.mily.basics.constant.Constant;
import cn.mily.basics.exception.UtilException;
import cn.mily.basics.service.impl.BasicServiceImpl;
import cn.mily.basics.utils.MD5Utils;
import cn.mily.basics.utils.StrUtils;
import cn.mily.user.domain.LoginInfo;
import cn.mily.user.domain.User;
import cn.mily.user.domain.dto.RegInfoDto;
import cn.mily.user.mapper.LoginInfoMapper;
import cn.mily.user.mapper.UserMapper;
import cn.mily.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends BasicServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional(readOnly = true)
    public void checkPhone(String phone) throws Exception {
        /*判断手机号是否为空*/
        if(StringUtils.isEmpty(phone)){
            throw new UtilException("手机号不能为空！");
        }else{
            /*手机号不为空*/
            /*检查是否注册过*/
            User user = userMapper.findByPhone(phone);
            if(user!=null){
               throw new UtilException("此手机号，已被注册！");
            }
        }
    }

    /**
     * 注册  +  效验
     * @param regInfo 注册信息
     */
    @Override
    @Transactional
    public void registerUser(RegInfoDto regInfo) throws UtilException {
        /*手机号是否为空*/
        if(StringUtils.isEmpty(regInfo.getPhone())){
            throw new UtilException("请填写手机号！");
        }else{/*判断注册了否*/
            User user = userMapper.findByPhone(regInfo.getPhone());
            if(user!=null){
                throw new UtilException("手机号已注册！");
            };
        }
        /*获取手机号验证码*/
        String verCode =(String)redisTemplate.opsForValue().get(regInfo.getPhone()+":"+ Constant.USER_REG);
        /*验证码是否为空*/
        if(StringUtils.isEmpty(regInfo.getVerCode())){
            throw new UtilException("验证码未填写！！！");
        };
        if(StringUtils.isEmpty(verCode)){
            throw new UtilException("验证码未获取！！！");
        };
        System.out.println(verCode);
        /*验证码是否过期*/
        if(StringUtils.isEmpty(verCode.split(":")[0])){
            throw new UtilException("验证码已过期！");
        }else{/*验证码未过期*/
            if(!regInfo.getVerCode().toUpperCase().equals(verCode.split(":")[0].toUpperCase())){
                throw new UtilException("验证码错误！");
            }
        }
        /*密码不能为空*/
        if(StringUtils.isEmpty(regInfo.getPassword())){
            throw new UtilException("密码不能为空！");
        }
        /*确认密码未填写*/
        if(StringUtils.isEmpty(regInfo.getPasswordSure())){
            throw new UtilException("请填写确认密码！");
        }
        /*两次密码不一致*/
        if(!regInfo.getPassword().equals(regInfo.getPasswordSure())){
            throw new UtilException("两次输入的密码不一致！");
        }
        User user = createUser(regInfo);
        /*效验完成注册用户*/
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user,loginInfo);
        loginInfoMapper.add(loginInfo);
        user.setLogininfo_id(loginInfo);
        userMapper.add(user);
    }

    /**
     * 邮箱发送验证码
     * @param email
     */
    @Override
    public void sendByEmail(String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        //设置发送人
        message.setFrom("1065119712@qq.com");
        //邮件主题
        message.setSubject("平台登录验证码！");
        /*验证码随机产生*/
        String s = StrUtils.getComplexRandomString(4);
        /*保存redis中   5分钟生存周期*/
        redisTemplate.opsForValue().set(email+":"+Constant.USER_EMAIL, s,5, TimeUnit.MINUTES);
        //邮件内容
        message.setText("您的验证码为："+s+"请在五分钟内完成登录。");
        //收件人
        message.setTo(email);
        /*发送*/
        javaMailSender.send(message);
    }

    /**
     * 登录信息封装User
     * @param regInfo 登录信息
     * @return 用户对象
     */
    public User createUser(RegInfoDto regInfo){
        User user = new User();
        user.setPhone(regInfo.getPhone());
        user.setSalt(StrUtils.getComplexRandomString(10));
        user.setPassword(MD5Utils.encrypByMd5(regInfo.getPassword()+user.getSalt()));
        return user;
    }
}
